#!/usr/bin/env python
# -*- coding: utf-8 -*-

from multiprocessing import Pool
import os, time, random
from datetime import datetime

def worker(id):
    t_start = time.time()
    print("[%s]Worker-%d[%d] is running..."%(datetime.now(),id, os.getpid()))
    time.sleep(random.random() * 5)
    t_stop = time.time()
    print("[%s]Worker-%d[%d] finished, spent %0.2f seconds..."%(datetime.now(),id, os.getpid(), t_stop-t_start))

po = Pool(3)   #分配了3个进程给进程池，只有当进程池里有空闲进程时才会处理新的请求
for i in range(10):
    po.apply_async(worker,args=(i,))    #异步处理，将所有请求一次过分配给进程池处理，非阻塞
    # po.apply(worker,args=(i,))  #同步执行，阻塞等待一个进程处理结束后再分配新的进程执行
    print(str(i)+'-'*100)
po.close()    #关闭进程池，不再接收新的请求，已经接收的请求会继续等待处理直到处理完成
po.join()     #主进程会等待所有进程处理结束
